package org.wzy.springcloud.feign.web.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.wzy.springcloud.feign.api.base.BaseLogger;
import org.wzy.springcloud.feign.api.domain.Person;
import org.wzy.springcloud.feign.api.service.PersonService;

import java.util.Collection;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>{@link PersonService} 服务提供者，可以实现{@link PersonService} 接口，也可以不实现。</p>
 * <p>
 * 本项目中的 application.properties 文件中定义了 person-service，@FeignClient 注解会将API暴露出去
 * <p>而person-client项目中指定的{@link EnableFeignClients} 注解则会依据指定class寻找对应的API
 * <p>一定要保证契约一致(即url相同)</p>
 * <p>
 * <p>注意
 * <li>{@link HystrixCommand#fallbackMethod()} A fallback method should be defined in the same class where is HystrixCommand.
 *
 * @author wzy_h
 * @version 1.0
 * @date 23:14 2017/11/20
 */
@RestController
public class PersonProviderController extends BaseLogger {

    @Autowired
    private Environment environment;

    private Map<Long, Person> map = new ConcurrentHashMap<>();

    @PostMapping(value = "/person/save")
    public String save(@RequestBody Person person) {
        map.putIfAbsent(person.getId(), person);
        return "person/save 接口调用、保存成功！调用的服务器端口为：" + environment.getProperty("server.port");
    }

    @GetMapping("/person/find/all")
    public Collection<Person> personFindAll() {
        int value = new Random().nextInt(200);
        System.out.println("personFindAll() costs " + value + " ms.");
        try {
            Thread.sleep(value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("当前服务端口是：" + environment.getProperty("server.port"));
        return map.values();
    }
}
